package Tree;

public class 删除二叉搜索树中的节点 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (root.val == key) {
            if (root.left == null && root.right == null) return null;
            else if (root.left != null && root.right == null) return root.left;
            else if (root.left == null && root.right != null) return root.right;
            else {
                TreeNode cur = root.left;
                while (cur.right != null) cur = cur.right;
                cur.right = root.right;
                return root.left;
            }
        }
        if (root.val < key) root.right = deleteNode(root.right, key);
        if (root.val > key) root.left = deleteNode(root.left, key);
        return root;
    }
}
